package client;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @file Server_Response.java
 *
 * @version 0.8
 * @author James Dibble 10009689
 * 
 * Latest Source:
 * http://code.google.com/p/csp-server/source/browse/trunk/
 *                                        Server/src/client/Server_Response.java
 */
public class Server_Response implements Runnable {
    // <editor-fold defaultstate="collapsed" desc="Attributes">
    private Socket sSocket;
    private Client_Response clientResponse;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Constructors">
    /**
     * Create an object that listens on a socket for messages from the server.
     * @param socket
     * @throws IOException 
     */
    public Server_Response(Socket socket) throws IOException {
        sSocket = socket;
        clientResponse = new Client_Response(sSocket);
        new Thread(clientResponse).start();
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Methods">
    @Override
    public void run() {
        try {
            BufferedReader brServerInput = new BufferedReader(
                                               new InputStreamReader(
                                                   sSocket.getInputStream()
                                               )
                                           );
            String strServerResponse = brServerInput.readLine();
            while (sSocket.isConnected() && strServerResponse != null) {
                System.out.println(String.format("Server: %s",
                        strServerResponse));
                System.out.print("Client: ");
                strServerResponse = brServerInput.readLine();
                if (strServerResponse.matches("FILE_INCOMING:[0-9]+")) {
                    int tempFileSize = 
                            Integer.parseInt(
                            strServerResponse.replace("FILE_INCOMING:", "")
                            );
                    String strTempFileName = 
                        brServerInput.readLine().replace("FILE_INCOMING:", "");
                    this.DownloadFile(strTempFileName, tempFileSize);
                    strServerResponse = brServerInput.readLine();
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace(System.out);
            System.out.println("Could not open stream to Server.  Closing..");
        } catch (NullPointerException npEx){
            
        } finally{
            try {
                clientResponse.Disconnect();
            } catch (IOException ex) {
                Logger.getLogger(
                   Server_Response.class.getName()).log(Level.SEVERE, null, ex);
            }
            clientResponse.interrupt();
            System.out.println("Server Disconnected.");
        }
    }

    /**
     * Get a file from the server and save it to the specified name in the
     * current working directory.
     * 
     * @param strFileName
     * @param intFileLength
     * @throws SocketException
     * @throws IOException 
     */
    public void DownloadFile(String strFileName, int intFileLength) 
                                           throws SocketException, IOException {
        File recievedFile = new File(strFileName);
        if (!recievedFile.exists()) {
            recievedFile.createNewFile();
        }
        FileOutputStream fosFile = new FileOutputStream(recievedFile);
        byte[] byteBuff = new byte[intFileLength];
        sSocket.getInputStream().read(byteBuff,0,intFileLength);
        fosFile.write(byteBuff);
        fosFile.flush();
        fosFile.close();
    }// </editor-fold>
}
